import { isShallow, type Ref } from "vue";

/**
 * 向数组中添加或更新一个元素
 * @param array
 * @param item
 * @param predicate
 */
export function addOrUpdate<T>(array: Ref<T[]>, item: T, predicate: (item: T, index: number, array: T[]) => boolean) {
  const shallow = isShallow(array);
  const copy = shallow ? [...array.value] : array.value;
  const idx = copy.findIndex(predicate);
  if (idx !== -1) {
    copy[idx] = item;
  } else {
    copy.push(item);
  }
  shallow && (array.value = copy);
}
